<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="2000" :class-name="'sub-navbar ' + statusMap[postForm.status]">
        <Original v-model="postForm.origin" />
        <CommentDropdown v-model="postForm.comment" />
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          草稿
        </el-button>
      </sticky>
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                Title
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-bottom: 40px;" prop="description" label-width="90px" label="文章简介:">
          <el-input v-model="postForm.description" :rows="1" type="textarea" class="article-textarea" maxlength="200" autosize placeholder="文章简介" />
          <span v-show="descriptionLength" class="word-counter">{{ descriptionLength }}words</span>
        </el-form-item>
        <el-form-item style="margin-bottom: 40px;" prop="keywords" label-width="90px" label="文章关键字:">
          <el-input v-model="postForm.keywords" :rows="1" type="textarea" class="article-textarea" autosize placeholder="文章关键字" />
          <span v-show="keywordsLength" class="word-counter">{{ keywordsLength }}words</span>
        </el-form-item>
        <el-form-item prop="content" style="margin-bottom: 30px;">
          <!--<Tinymce ref="editor" v-model="postForm.content" :height="400" />-->
          <!--          <editor-m-d :id="id" ref="editor" v-model="postForm.content" />-->
          <mavon-editor
            ref="md"
            v-model="postForm.content"
            @imgAdd="imgAdd"
          />
        </el-form-item>
        <el-form-item prop="categoryId" label="分类：" style="margin-bottom: 30px;">
          <el-select v-model="postForm.categoryId" clearable placeholder="请选择">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="tagIds" label="标签：" style="margin-bottom: 30px;">
          <el-select
            v-model="postForm.tagIds"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择文章标签"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getImgList">选择图片</el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="postForm.thumb" />
        </el-form-item>
        <el-form-item prop="thumb" style="margin-bottom: 30px;">
          <Upload v-model="postForm.thumb" />
        </el-form-item>
      </div>
    </el-form>
    <el-dialog
      :visible.sync="dialogVisible"
      center
    >
      <ul style="list-style: none;overflow: hidden;">
        <li
          v-for="item in imgList"
          :key="item.key"
          style="width:100px;float:left;margin-right:15px;line-height:20px;"
        >
          <img
            style="border-radius:50%;width: 80px;height: 80px"
            :src="'https://img.luoyuanxiangvip.com/' + item.key"
            @click="imgUrl(item.key)"
          >
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
// import Tinymce from '@/components/Tinymce'
// import EditorMD from '@/components/EditorMD'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { CommentDropdown, Original } from './Dropdown'
import { saveOrUpdate, info, feachImgList } from '@/api/article'
import { MessageBox } from 'element-ui'
import { uploadFile } from '@/api/article'
const defaultForm = {
  id: undefined,
  categoryId: '', // 分类id
  tagIds: [], // 标签
  status: false, // 状态
  title: '', // 文章题目
  description: '', // 文章简介，最多200字
  keywords: '', // 文章关键字，优化搜索
  content: '', // 文章内容
  thumb: '', // 文章图片
  comment: true, // 是否开启评论
  origin: 0 // 【0 原创】【1 转载】【2 混合】
}

export default {
  name: 'ArticleDetail',
  components: { MDinput, Upload, Sticky, CommentDropdown, Original },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateArray = (rule, value, callback) => {
      if (value.length === 0) {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      imgList: [],
      id: 'editor',
      statusMap: {
        true: 'published',
        false: 'draft'
      },
      categoryOptions: [],
      tagOptions: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        title: [{ validator: validateRequire }],
        description: [{ validator: validateRequire }],
        keywords: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        thumb: [{ validator: validateRequire }],
        categoryId: [{ validator: validateRequire }],
        tagIds: [{ validator: validateArray }]
      },
      tempRoute: {}
    }
  },
  computed: {
    descriptionLength() {
      return this.postForm.description.length
    },
    keywordsLength() {
      return this.postForm.keywords.length
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.tempRoute = Object.assign({}, this.$route)
    this.getCategoryAndTag()
  },
  methods: {
    getImgList() {
      feachImgList().then(res => {
        this.imgList = res.result
        this.dialogVisible = true
      })
    },
    getCategoryAndTag() {
      this.categoryOptions = this.$store.getters.categoryList
      this.tagOptions = this.$store.getters.tagList
    },
    fetchData(id) {
      info(id).then(res => {
        if (res.code === 0) {
          this.postForm = res.result
        }
      })
    },
    submitForm() {
      console.info(this.postForm)
      this.postForm.status = true
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          saveOrUpdate(this.postForm).then(res => {
            if (res.code === 0) {
              MessageBox.confirm('文章发布成功！是否返回文章列表？', '提示', {
                confirmButtonText: '文章列表',
                cancelButtonText: '继续添加文章',
                type: 'warning'
              }).then(() => {
                this.$router.push('/article/article')
              }).catch(() => {
                if (this.postForm.id) {
                  this.$router.push('/article/create')
                } else {
                  this.postForm = Object.assign({}, defaultForm)
                }
              })
              this.loading = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      this.postForm.status = false
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.loading = true
      saveOrUpdate(this.postForm).then(res => {
        if (res.code === 0) {
          MessageBox.confirm('草稿保存！是否返回文章列表？', '提示', {
            confirmButtonText: '文章列表',
            cancelButtonText: '继续修改文章',
            type: 'warning'
          }).then(() => {
            this.$router.push('/article/article')
          })
          this.loading = false
        }
      })
    },
    imgUrl(item) {
      this.postForm.thumb = `https://img.luoyuanxiangvip.com/${item}`
      this.dialogVisible = false
    },
    imgAdd(pos, $file) {
      const formData = new FormData()
      formData.append('file', $file)
      uploadFile(formData).then(res => {
        this.$refs.md.$img2Url(pos, res.result)
        this.$notify({
          title: '图片',
          message: '图片上传成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
